//
//  UIButton+Ext.swift
//  TimMusic
//
//  Created by nkl on 2024/10/14.
//

import Foundation
import UIKit

extension UIButton {
    
    func setLocalizedImageAndTitle(image: UIImage?, title: String, for state: UIControl.State) {
        self.setImage(image?.imageFlippedForRightToLeftLayoutDirection(), for: state)
        self.setTitle(title, for: state)
        
        // 根据布局方向设置 titleEdgeInsets 和 imageEdgeInsets
        if UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute) == .rightToLeft {
            self.titleEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 10)
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0)
            self.contentHorizontalAlignment = .right
        } else {
            self.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: -10)
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
            self.contentHorizontalAlignment = .leading
        }
    }
    
    func setLocalizedImage(_ image: UIImage?, for state: UIControl.State) {
        guard let image = image else {
            self.setImage(nil, for: state)
            return
        }
        self.setImage(image.imageFlippedForRightToLeftLayoutDirection(), for: state)
    }

    func setLocalizedBackgroundImage(_ image: UIImage?, for state: UIControl.State) {
        guard let image = image else {
            self.setBackgroundImage(nil, for: state)
            return
        }
        self.setBackgroundImage(image.imageFlippedForRightToLeftLayoutDirection(), for: state)
    }
}
